// Package middleware
// @Author zhongxc
// @Date 2024/1/15 16:21:00
// @Desc
package middleware

import (
	"context"
	"net/http"
	"strings"
	"zhongxc.cc/admin-common/tools"
)

type AuthorizeMiddleware struct {
}

func NewAuthorizeMiddleware() *AuthorizeMiddleware {
	return &AuthorizeMiddleware{}
}

func (m *AuthorizeMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(writer http.ResponseWriter, request *http.Request) {
		// 创建一个新的上下文
		ctx := context.Background()

		// 校验token
		tokenString := request.Header.Get("Authorization")
		if tokenString == "" || !strings.HasPrefix(tokenString, "Bearer ") {
			m.responseWriter(writer)
			return
		}
		tokenArray := strings.Split(tokenString, " ")
		if len(tokenArray) <= 1 {
			m.responseWriter(writer)
			return
		}
		// logx.Infof("%v", tokenArray)
		myClaims, err := tools.ParseToken(tokenArray[1])
		if err != nil {
			m.responseWriter(writer)
			return
		}
		// 使用上下文来存储
		ctx = context.WithValue(ctx, "userinfo", myClaims)

		next(writer, request.WithContext(ctx))
	}
}

func (m *AuthorizeMiddleware) responseWriter(writer http.ResponseWriter) {
	writer.WriteHeader(http.StatusUnauthorized)
	_, _ = writer.Write([]byte(`{"code": 401, "message": "Token is invalid or has expired"}`))
}
